package com.wephone.Student.ui;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;

import com.loopj.android.http.RequestParams;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.wephone.Student.R;
import com.wephone.Student.bean.FlyTogetherListResponse;
import com.wephone.Student.bean.data.FlyTogetherInfoData;
import com.wephone.Student.network.HttpClient;
import com.wephone.Student.network.MyResponseHandler;
import com.wephone.Student.util.Constants;
import com.wephone.Student.util.PullToRefreshView;
import com.wephone.Student.util.PullToRefreshView.OnFooterRefreshListener;
import com.wephone.Student.util.PullToRefreshView.OnHeaderRefreshListener;
import com.wephone.Student.util.RoundImageView;

public class FlyTogetherActivity extends BaseActivity {
	private PullToRefreshView pullToRefreshListView;
	private ListView listView;
	private ListViewAdapter adapter;
	private List<FlyTogetherInfoData> results = new ArrayList<FlyTogetherInfoData>();
	private String fFrom;
	private String fTo;
	private String startTime;
	private String fTitle;
	
	private MyResponseHandler getHandler(){
		MyResponseHandler handler = new MyResponseHandler(FlyTogetherActivity.this,FlyTogetherListResponse.class){
			@Override
			public void onSuccess(String result) {
				super.onSuccess(result);
				
				if(getDataSuccess){
					FlyTogetherListResponse res = (FlyTogetherListResponse)response;
					
					if(adapter.pageIdx>=res.getTotalPage() || res.getData().size()<Constants.PAGE_SIZE){
						adapter.hasMore = false;
					}else{
						adapter.pageIdx++;
					}
					results.addAll(res.getData());
					adapter.notifyDataSetChanged();
				}
			}
		};
		return handler;
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if(requestCode==11 && resultCode==111){
			findViewById(R.id.progressBar).setVisibility(View.VISIBLE);
			fFrom = data.getStringExtra("flyFrom");
			fTo = data.getStringExtra("flyTo");
			startTime = data.getStringExtra("startTime");
			fTitle = data.getStringExtra("fTitle");
//			System.out.println("----fFrom---"+fFrom);
//			System.out.println("----fTo---"+fTo);
//			System.out.println("----fDate---"+fDate);
			
			results.clear();
			adapter.notifyDataSetChanged();
			adapter.pageIdx = 1;
			adapter.hasMore = true;
			
			RequestParams params = new RequestParams();
			params.put("Page", "1");
			params.put("PageSize", ""+Constants.PAGE_SIZE);
			if(!TextUtils.isEmpty(fFrom)){
				params.put("fFrom", fFrom);
			}
			if(!TextUtils.isEmpty(fTo)){
				params.put("fTo", fTo);
			}
			if(!TextUtils.isEmpty(startTime)){
				params.put("startTime", startTime);
			}
			if(!TextUtils.isEmpty(fTitle)){
				params.put("fTitle", fTitle);
			}
			HttpClient.getInstance().get(Constants.API_GET_FLY_TOGETHER_LIST_URL, params, getHandler());
		}else if(requestCode==22 && resultCode==222){
			findViewById(R.id.progressBar).setVisibility(View.VISIBLE);
			results.clear();
			adapter.notifyDataSetChanged();
			adapter.pageIdx = 1;
			adapter.hasMore = true;
			
			RequestParams params = new RequestParams();
			params.put("Page", "1");
			params.put("PageSize", ""+Constants.PAGE_SIZE);
			HttpClient.getInstance().get(Constants.API_GET_FLY_TOGETHER_LIST_URL, params, getHandler());
		}
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_fly_together);
		
		init();
	}
	
	private void init(){
		listView = (ListView)findViewById(R.id.listview);
		adapter = new ListViewAdapter();
		listView.setAdapter(adapter);
		listView.setOnItemClickListener(new ListView.OnItemClickListener(){
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				FlyTogetherDetailActivity.data = results.get(arg2);
				startActivity(new Intent(getApplicationContext(),FlyTogetherDetailActivity.class));
			}});
		
		findViewById(R.id.btn_back).setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				finish();
			}
		});
		findViewById(R.id.btn_top_right_1).setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				startActivityForResult(new Intent(getApplicationContext(),CreateFlyTogetherActivity.class),22);
			}
		});
		findViewById(R.id.btn_top_right_2).setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				startActivityForResult(new Intent(getApplicationContext(),FlyTogetherSearchActivity.class),11);
			}
		});
		pullToRefreshListView = (PullToRefreshView)findViewById(R.id.pull_refresh_listview);
		pullToRefreshListView.setOnHeaderRefreshListener(new OnHeaderRefreshListener() {
			@Override
			public void onHeaderRefresh(PullToRefreshView view) {
				results.clear();
				adapter.hasMore = true;
				adapter.pageIdx = 1;
				
				RequestParams params = new RequestParams();
				params.put("Page", "1");
				params.put("PageSize", ""+Constants.PAGE_SIZE);
				HttpClient.getInstance().get(Constants.API_GET_FLY_TOGETHER_LIST_URL, params, getHandler());
			}
		});
		pullToRefreshListView.setOnFooterRefreshListener(new OnFooterRefreshListener() {
			@Override
			public void onFooterRefresh(PullToRefreshView view) {
				if(!adapter.hasMore){
					pullToRefreshListView.onFooterRefreshComplete();
					return;
				}
				RequestParams params = new RequestParams();
				params.put("Page", ""+adapter.pageIdx);
				params.put("PageSize", ""+Constants.PAGE_SIZE);
				if(!TextUtils.isEmpty(fFrom)){
					params.put("fFrom", fFrom);
				}
				if(!TextUtils.isEmpty(fTo)){
					params.put("fTo", fTo);
				}
				if(!TextUtils.isEmpty(startTime)){
					params.put("startTime", startTime);
				}
				if(!TextUtils.isEmpty(fTitle)){
					params.put("fTitle", fTitle);
				}
				HttpClient.getInstance().get(Constants.API_GET_FLY_TOGETHER_LIST_URL, params, getHandler());
			}
		});
		
		RequestParams params = new RequestParams();
		params.put("Page", "1");
		params.put("PageSize", ""+Constants.PAGE_SIZE);
		HttpClient.getInstance().get(Constants.API_GET_FLY_TOGETHER_LIST_URL, params, getHandler());
	}
	
	private class ListViewAdapter extends BaseAdapter{
		public int pageIdx = 1;
		public boolean hasMore = true;
		private SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日");
		
		@Override
		public int getCount() {
			return results.size();
		}

		@Override
		public Object getItem(int position) {
			return null;
		}

		@Override
		public long getItemId(int position) {
			return 0;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			if(convertView==null){
				convertView = getLayoutInflater().inflate(R.layout.include_fly_together_list_item, null);
			}
			FlyTogetherInfoData flyInfo = results.get(position);
			TextView itemName = (TextView)convertView.findViewById(R.id.item_name);
			itemName.setText(flyInfo.getfTitle());
			TextView itemCountry = (TextView)convertView.findViewById(R.id.item_country);
			itemCountry.setText("From "+flyInfo.getfFrom()+" To "+flyInfo.getfTo());
			TextView flyDate = (TextView)convertView.findViewById(R.id.item_fly_date);
			flyDate.setText(sdf.format(new Date(Long.parseLong(flyInfo.getfTime())*1000)));
			TextView itemSign = (TextView)convertView.findViewById(R.id.item_signature);
			itemSign.setText(flyInfo.getfDetail());
			
			RoundImageView itemImage = (RoundImageView)convertView.findViewById(R.id.item_image);
			if(!TextUtils.isEmpty(flyInfo.getuInfo().getuIcon())){
				DisplayImageOptions options = new DisplayImageOptions.Builder()
		        .showStubImage(R.drawable.default_user_logo)
		        .showImageOnFail(R.drawable.default_user_logo)
		        .bitmapConfig(Bitmap.Config.ARGB_8888)
		        .cacheInMemory()
		        .cacheOnDisc()
//		        .displayer(new RoundedBitmapDisplayer(1000))
		        .build();
				String endStr = flyInfo.getuInfo().getuIcon().substring(flyInfo.getuInfo().getuIcon().lastIndexOf("."));
				imageLoader.displayImage(Constants.IMAGE_PHOTO_SERVER_PATH+flyInfo.getuInfo().getuIcon().replace(endStr, "_150_150"+endStr), itemImage, options);
//				imageLoader.displayImage(Constants.IMAGE_PHOTO_SERVER_PATH+flyInfo.getuInfo().getuIcon(), itemImage, options);
			}else{
				itemImage.setImageResource(R.drawable.default_user_logo);
			}
			
////			load more
//			if(position>=results.size()-1 && hasMore){
//				RequestParams params = new RequestParams();
//				params.put("Page", ""+pageIdx);
//				params.put("PageSize", ""+Constants.PAGE_SIZE);
//				if(!TextUtils.isEmpty(fFrom)){
//					params.put("fFrom", fFrom);
//				}
//				if(!TextUtils.isEmpty(fTo)){
//					params.put("fTo", fTo);
//				}
//				if(!TextUtils.isEmpty(startTime)){
//					params.put("startTime", startTime);
//				}
//				if(!TextUtils.isEmpty(fTitle)){
//					params.put("fTitle", fTitle);
//				}
//				HttpClient.getInstance().get(Constants.API_GET_FLY_TOGETHER_LIST_URL, params, getHandler());
//			}
			return convertView;
		}		
	}

	@Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // TODO Auto-generated method stub
        menu.add("刷新");
        return super.onCreateOptionsMenu(menu);
    }
	
	@Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // TODO Auto-generated method stub
        if(item.getItemId() == 0){
            findViewById(R.id.progressBar).setVisibility(View.VISIBLE);
            
            adapter.pageIdx = 1;
            adapter.hasMore = true;
            results.clear();
			adapter.notifyDataSetChanged();
			
			fFrom = "";
			fTo = "";
			startTime = "";
			fTitle = "";
			
    		RequestParams params = new RequestParams();
    		params.put("Page", "1");
    		params.put("PageSize", ""+Constants.PAGE_SIZE);
    		HttpClient.getInstance().get(Constants.API_GET_FLY_TOGETHER_LIST_URL, params, getHandler());
        } 
        return true;
    }
	
}
